<template>
  <el-card class="user-info-card" shadow="never">
    <div class="section-header">
      <h3 class="section-title">基本信息</h3>
    </div>
    <el-form label-width="100px" class="profile-form">
      <el-form-item label="用户名/昵称">
        <el-input v-model="editUser.username" placeholder="请输入您的用户名或昵称" />
      </el-form-item>
    
      <el-form-item label="手机号码">
        <el-input v-model="editUser.phone" placeholder="请输入您的手机号码" />
      </el-form-item>
      
      <el-form-item label="邮箱地址">
        <el-input v-model="editUser.email" :disabled="true" placeholder="您的邮箱地址"/>
      </el-form-item>

      <el-form-item label="头像上传">
        <div class="avatar-upload">
          <div class="avatar-preview-container">
            <img :src="avatarPreview" class="avatar-preview" />
            <div class="avatar-overlay">
              <el-icon><Edit /></el-icon>
            </div>
          </div>
          <el-upload
            class="avatar-upload-btn"
            :show-file-list="false"
            :before-upload="handleAvatarChange"
          >
            <el-button type="primary" plain>更换头像</el-button>
          </el-upload>
        </div>
      </el-form-item>
      
      <el-form-item label="证件信息">
        <el-input v-model="editUser.idCard" placeholder="身份证/护照号" />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="saveUserInfo">保存信息</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    
    <el-divider>
      <el-icon><UserFilled /></el-icon>
      <span style="margin-left: 8px">常住旅客信息管理</span>
    </el-divider>
    
    <div class="travelers-section">
      <el-table 
        :data="travelers" 
        style="width: 100%" 
        border 
        stripe
        :header-cell-style="{background: '#f5f7fa'}"
      >
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column prop="idCard" label="证件号" min-width="180" />
        <el-table-column prop="phone" label="手机号" min-width="130" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" text @click="editTraveler(scope.row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button size="small" type="danger" text @click="removeTraveler(scope.row)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="add-traveler-section">
        <el-button type="primary" @click="addTraveler" class="add-traveler-btn">
          <el-icon><Plus /></el-icon> 添加旅客
        </el-button>
      </div>
    </div>
  </el-card>

  <el-dialog 
    v-model="addTravelerDialog" 
    title="添加旅客" 
    width="500px"
    destroy-on-close
    center
  >
    <el-form label-width="80px" :model="newTraveler">
      <el-form-item label="姓名" required>
        <el-input v-model="newTraveler.name" placeholder="请输入旅客姓名" />
      </el-form-item>
      <el-form-item label="证件号" required>
        <el-input v-model="newTraveler.idCard" placeholder="请输入有效的证件号码" />
      </el-form-item>
      <el-form-item label="手机号" required>
        <el-input v-model="newTraveler.phone" placeholder="请输入联系电话" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addTravelerDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAddTraveler">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑旅客对话框 -->
  <el-dialog 
    v-model="editTravelerDialog" 
    title="编辑旅客" 
    width="500px"
    destroy-on-close
    center
  >
    <el-form label-width="80px" :model="editingTraveler">
      <el-form-item label="姓名" required>
        <el-input v-model="editingTraveler.name" placeholder="请输入旅客姓名" />
      </el-form-item>
      <el-form-item label="证件号" required>
        <el-input v-model="editingTraveler.idCard" placeholder="请输入有效的证件号码" />
      </el-form-item>
      <el-form-item label="手机号" required>
        <el-input v-model="editingTraveler.phone" placeholder="请输入联系电话" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editTravelerDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmEditTraveler">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 删除确认对话框 -->
  <el-dialog
    v-model="deleteConfirmDialog"
    title="删除确认"
    width="400px"
    center
  >
    <p>确定要删除旅客 <strong>{{ travelerToDelete?.name }}</strong> 的信息吗？此操作不可恢复。</p>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deleteConfirmDialog = false">取消</el-button>
        <el-button type="danger" @click="confirmDeleteTraveler">确定删除</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { apiUpdateUserInfo, apiAddTraveler, apiGetTravelers, apiUploadAvatar, apiUpdateTraveler, apiDeleteTraveler } from '@/api/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Plus, UserFilled } from '@element-plus/icons-vue'

const props = defineProps<{
  user: any
}>()

const emit = defineEmits(['update:user'])  // 定义一个事件，用于更新父组件的 user 数据

const editUser = ref<any>({...props.user})
const avatarPreview = ref(props.user?.avatar || 'https://cdn-icons-png.flaticon.com/512/149/149071.png')
const travelers = ref<any[]>([])
const addTravelerDialog = ref(false)
const newTraveler = ref({ name: '', idCard: '', phone: '' })

// 编辑旅客相关
const editTravelerDialog = ref(false)
const editingTraveler = ref<{ id: string, name: string, idCard: string, phone: string }>({ id: '', name: '', idCard: '', phone: '' })

// 删除旅客相关
const deleteConfirmDialog = ref(false)
const travelerToDelete = ref<{ id: string, name: string } | null>(null)

// 获取旅客列表
async function fetchTravelers() {
  try {
    const res: any = await apiGetTravelers()
    if (res.code === 200) {
      travelers.value = res.data || []
    }
  } catch (e) {
    console.error('获取旅客列表失败:', e)
  }
}

function handleAvatarChange(file: any) {
  const reader = new FileReader()
  reader.onload = e => {
    avatarPreview.value = e.target?.result as string
  }
  reader.readAsDataURL(file)
  return false
}

function resetForm() {
  editUser.value = {...props.user}
  avatarPreview.value = props.user?.avatar || 'https://cdn-icons-png.flaticon.com/512/149/149071.png'
  ElMessage.info('已重置表单')
}

async function uploadAvatar(avatarBase64: string): Promise<string | null> {
  try {
    const imageBlob = dataURLtoBlob(avatarBase64)
    const formData = new FormData()
    formData.append('image', imageBlob, 'avatar.png')
    const res: any = await apiUploadAvatar(formData)
    if (res.code === 200) {
      return res.data
    } else {
      ElMessage.error('头像上传失败: ' + res.msg)
      return null
    }
  } catch (e: any) {
    ElMessage.error('头像上传失败: ' + e.message)
    return null
  }
}

function dataURLtoBlob(dataurl: string): Blob {
  const arr = dataurl.split(',')
  const mime = arr[0].match(/:(.*?);/)?.[1]
  if (!mime) {
    throw new Error('Invalid base64 format')
  }
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

async function saveUserInfo() {
  try {
    if (avatarPreview.value && avatarPreview.value.startsWith('data:image')) {
      const avatarUrl = await uploadAvatar(avatarPreview.value)
      if (!avatarUrl) return
      editUser.value.avatar = avatarUrl
    }
    const res: any = await apiUpdateUserInfo(editUser.value)
    if (res.code === 200) {
      emit('update:user', { ...editUser.value })
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  } catch (e: any) {
    ElMessage.error('保存失败: ' + e.message)
  }
}

async function confirmAddTraveler() {
  if (!newTraveler.value.name || !newTraveler.value.idCard || !newTraveler.value.phone) {
    ElMessage.error('请填写完整信息')
    return
  }
  try {
    const res: any = await apiAddTraveler(newTraveler.value)
    if (res.code === 200) {
      ElMessage.success('添加成功')
      addTravelerDialog.value = false
      newTraveler.value = { name: '', idCard: '', phone: '' }
      fetchTravelers() // 重新获取旅客列表
    } else {
      ElMessage.error(res.msg || '添加失败')
    }
  } catch (e) {
    ElMessage.error('添加失败')
  }
}

function addTraveler() {
  addTravelerDialog.value = true
}

// 编辑旅客
function editTraveler(row: any) {
  editingTraveler.value = { ...row }
  editTravelerDialog.value = true
}

// 确认编辑旅客
async function confirmEditTraveler() {
  if (!editingTraveler.value.name || !editingTraveler.value.idCard || !editingTraveler.value.phone) {
    ElMessage.error('请填写完整信息')
    return
  }
  
  try {
    const res: any = await apiUpdateTraveler(editingTraveler.value)
    if (res.code === 200) {
      ElMessage.success('更新成功')
      editTravelerDialog.value = false
      fetchTravelers() // 重新获取旅客列表
    } else {
      ElMessage.error(res.msg || '更新失败')
    }
  } catch (e: any) {
    ElMessage.error('更新失败: ' + e.message)
  }
}

// 删除旅客
function removeTraveler(row: any) {
  travelerToDelete.value = { id: row.id, name: row.name }
  deleteConfirmDialog.value = true
}

// 确认删除旅客
async function confirmDeleteTraveler() {
  if (!travelerToDelete.value) return
  
  try {
    const res: any = await apiDeleteTraveler(travelerToDelete.value.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      deleteConfirmDialog.value = false
      fetchTravelers() // 重新获取旅客列表
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (e: any) {
    ElMessage.error('删除失败: ' + e.message)
  }
}

onMounted(() => {
  fetchTravelers()
})
</script>

<style scoped>
.user-info-card {
  border: none;
  box-shadow: none !important;
}

.section-header {
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  color: #303133;
  font-weight: 600;
  margin: 0;
}

.profile-form {
  max-width: 500px;
}

.avatar-upload {
  display: flex;
  align-items: center;
  gap: 24px;
}

.avatar-preview-container {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.avatar-preview-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border: 2px solid #ffffff;
  background: #f6f8fb;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-overlay .el-icon {
  color: white;
  font-size: 24px;
}

.avatar-upload-btn {
  margin-left: 0;
}

.travelers-section {
  margin-top: 24px;
}

.add-traveler-section {
  margin-top: 16px;
  display: flex;
  justify-content: flex-start;
}

.add-traveler-btn {
  margin-top: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

@media (max-width: 768px) {
  .avatar-upload {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .profile-form {
    width: 100%;
  }
}
</style> 